const svgCaptcha = require('svg-captcha');
const config = require('@/config/captcha')[process.env.NODE_ENV || 'development'];
const { createClient } = require('redis');

class CaptchaService {
  constructor() {
    this.store = new Map(); // 内存存储
    this.redisClient = null;

    // 生产环境才连接Redis
    if (config.store === 'redis') {
      this.redisClient = createClient({
        url: `redis://${config.redis.host}:${config.redis.port}`
      });
      this.redisClient.connect().catch(console.error);
    }
  }

  // 生成验证码
  generate() {
    const captcha = svgCaptcha.create({
      size: config.length,
      width: config.width,
      height: config.height,
      ignoreChars: config.ignoreChars,
      color: config.color,
      background: config.background
    });

    // 存储验证码文本
    const key = `captcha:${Date.now()}`;
    if (config.store === 'redis') {
      this.redisClient.set(key, captcha.text, { EX: config.redis.ttl });
      return { text: captcha.text, image: captcha.data, key };
    } else {
      this.store.set(key, captcha.text);
      return { text: captcha.text, image: captcha.data, key };
    }
  }

  // 验证验证码
  async verify(text, key) {
    let storedText;

    if (config.store === 'redis') {
      storedText = await this.redisClient.get(key);
      if (storedText) {
        await this.redisClient.del(key); // 验证后删除
      }
    } else {
      storedText = this.store.get(key);
      if (storedText) {
        this.store.delete(key); // 验证后删除
      }
    }

    if (!storedText) return false;
    return storedText.toLowerCase() === text.toLowerCase();
  }
}

module.exports = new CaptchaService();